package ai.chat2db.server.web.start.controller.oauth;

import ai.chat2db.server.domain.api.service.UserService;
import ai.chat2db.server.domain.repository.enums.LoginTypeEnum;
import ai.chat2db.server.tools.base.wrapper.result.ActionResult;
import ai.chat2db.server.tools.base.wrapper.result.DataResult;
import ai.chat2db.server.tools.common.model.LoginUser;
import ai.chat2db.server.tools.common.util.ContextUtils;
import ai.chat2db.server.web.start.config.oauth.OauthService;
import ai.chat2db.server.web.start.config.oauth.OauthUtil;
import ai.chat2db.server.web.start.controller.oauth.request.LoginRequest;
import cn.dev33.satoken.stp.StpUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Login authorization service
 *
 * @author Jiaju Zhuang
 */
@RestController
@RequestMapping("/api/oauth")
@Slf4j
public class OauthController {


    @Resource
    private UserService userService;


    /**
     * Login with username and password
     *
     * @param request plus
     * @return dd
     */
    @PostMapping("login_a")
    public DataResult<Object> login(@Validated @RequestBody LoginRequest request) {
        OauthService oauthService = OauthUtil.getDefaultOauthService();
        return DataResult.of(oauthService.doLogin(request));
    }

    /**
     * Sign out
     *
     * @return
     */
    @PostMapping("logout_a")
    public ActionResult logout() {
        StpUtil.logout();
        return ActionResult.isSuccess();
    }

    /**
     * user
     *
     * @return
     */
    @GetMapping("user")
    public DataResult<LoginUser> user() {
        return DataResult.of(getLoginUser());
    }

    /**
     * user
     *
     * @return
     */
    @GetMapping("user_a")
    public DataResult<LoginUser> usera() {
        return DataResult.of(getLoginUser());
    }

    private LoginUser getLoginUser() {
        return ContextUtils.queryLoginUser();
    }

}
